<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <title>用户列表</title>
    <link th:href="@{/layui/css/layui.css}" rel="stylesheet" media="all" />
    <link th:href="@{/layui/css/modules/laydate/default/laydate.css}" rel="stylesheet" media="all" />
    <link th:href="@{/layui/css/modules/layer/default/layer.css}" rel="stylesheet" media="all" />
</head><script th:src="@{/layui/layui.js}"></script>
<script th:src="@{/js/jquery.js}"></script>
<body>

<h1 class="press" align="center">
    用户列表
</h1>

<div class="userTable">
    <b>搜索姓名：</b>
    <div class="layui-inline">
        <input class="layui-input" name="userName" id="userNameReload" autocomplete="off">
    </div>
    <button class="layui-btn"  data-type="reload">搜索</button>
    <button button type="reset" class="layui-btn layui-btn-primary" onclick="reset()">重置</button>
</div>

<table class="layui-hide" id="demo" lay-filter="test"></table>

<style>
    .press {
        color: transparent;
        background-color : black;
        text-shadow : rgba(255,255,255,0.5) 0 5px 6px, rgba(255,255,255,0.2) 1px 3px 3px;
        -webkit-background-clip : text;
    }
</style>

<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="detail">查看</a>
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>




<!--用户编辑弹出层-->
<script type="text/html" id="edit_form">
    <div class="layui-col-md10" style="margin-left: 35px;margin-top: 20px">
        <form class="layui-form layui-form-pane" lay-filter="edit_form" action="">
            <div class="layui-form-item">
                <label class="layui-form-label">用户姓名</label>
                <div class="layui-input-block">
                    <input type="text" name="userName" required  lay-verify="required" placeholder="请输入用户姓名"
                           autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">用户年龄</label>
                <div class="layui-input-block">
                    <input type="text" name="userAge" required  lay-verify="required" placeholder="请输入用户年龄"
                           autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item" style="margin-top: 20px">
                <div class="layui-input-block">
                    <button class="layui-btn" lay-submit lay-filter="editForm">立即提交</button>
                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                </div>
            </div>

        </form>

    </div>
</script>

<!--用户查看弹出层-->
<script type="text/html" id="view_form">
    <div class="layui-col-md10" style="margin-left: 35px;margin-top: 20px">
        <form class="layui-form layui-form-pane" lay-filter="view_form" action="">
            <div class="layui-form-item">
                <label class="layui-form-label">用户姓名</label>
                <div class="layui-input-block">
                    <input type="text" name="userName" required  lay-verify="required"
                           autocomplete="off" class="layui-input" disabled="true">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">用户年龄</label>
                <div class="layui-input-block">
                    <input type="text" name="userAge" required  lay-verify="required"
                           autocomplete="off" class="layui-input" disabled="true">
                </div>
            </div>
        </form>

    </div>
</script>

<!--用户添加弹出层-->
<script type="text/html" id="add_form">
    <div class="layui-col-md10" style="margin-left: 35px;margin-top: 20px">
        <form class="layui-form layui-form-pane" lay-filter="add_form" action="">
            <div class="layui-form-item">
                <label class="layui-form-label">用户姓名</label>
                <div class="layui-input-block">
                    <input type="text" name="userName" required  lay-verify="required" placeholder="请输入用户姓名"
                           autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">用户年龄</label>
                <div class="layui-input-block">
                    <input type="text" name="userAge" required  lay-verify="required" placeholder="请输入用户年龄"
                           autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item" style="margin-top: 20px">
                <div class="layui-input-block">
                    <button class="layui-btn" lay-submit lay-filter="addForm">立即提交</button>
                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                </div>
            </div>

        </form>

    </div>
</script>

<script>

    /**
     * 重置搜索
     * **/
    function reset(){
        $("#userNameReload").val("");
        // 重新加载表格
        window.parent.location.reload();
    }

    layui.use(['laydate', 'laypage', 'layer', 'table', 'carousel', 'upload', 'element', 'slider','element','form'], function(){
        var laydate = layui.laydate //日期
            ,laypage = layui.laypage //分页
            ,layer = layui.layer //弹层
            ,table = layui.table //表格
            ,carousel = layui.carousel //轮播
            ,upload = layui.upload //上传
            ,element = layui.element //元素操作
            ,slider = layui.slider //滑块
            ,form = layui.form //表单
            ,element=layui.element //元素


        //执行一个 table 实例
        table.render({
            elem: '#demo'
            ,height: 560
            ,url: '/business/user/list' //数据接口
            ,title: '用户表'
            ,page: true //开启分页
            ,toolbar: 'default' //开启工具栏，此处显示默认图标，可以自定义模板，详见文档
            ,totalRow: true //开启合计行
            ,response: {
                statusCode: 200 //重新规定成功的状态码为 200，table 组件默认为 0
            }
            ,id: 'testReload'
            ,cols: [
                      [ //表头
                {type: 'checkbox', fixed: 'left'}
                ,{field: 'id', title: 'ID', width:250, sort: true, fixed: 'left', totalRowText: '合计：'}
                ,{field: 'userName', title: '用户名'}
                ,{field: 'userAge', title: '年龄'}
                ,{field: 'createTime', title: '创建时间'}
                ,{fixed: 'right', width: 165, align:'center', toolbar: '#barDemo'}
                     ]
                   ]
            ,parseData: function(res){ //res 即为原始返回的数据
            return {
                "code": res.code, //解析接口状态
                "msg": res.message, //解析提示文本
                "count": res.data.total, //解析数据长度
                "data": res.data.records //解析数据列表
            };
        }
        });

        // 搜索表格重载
        var $ = layui.$, active = {
            reload: function(){
                var userNameReload = $('#userNameReload');

                //执行重载
                table.reload('testReload', {
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                    ,where: {
                        userName: userNameReload.val()
                    }
                }, 'data');
            }
        };

        $('.userTable .layui-btn').on('click', function(){
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });


        //监听头工具栏事件
        table.on('toolbar(test)', function(obj){
            var checkStatus = table.checkStatus(obj.config.id)
                ,data = checkStatus.data; //获取选中的数据
            switch(obj.event){
                case 'add':
                    // 打开添加弹窗
                    layer.open({
                        title:'添加用户',
                        type:1,
                        area:['420px','330px'],
                        content:$('#add_form').html()
                    })
                    form.render() //更新渲染表单

                    // 添加用户提交
                    form.on('submit(addForm)',function(message){
                        console.log(message.field);


                        var addObj={
                            "userAge":message.field.userAge,
                            "userName":message.field.userName
                        };

                        $.ajax({
                            url:"/business/user/add",
                            type:"POST",
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            data: JSON.stringify(addObj),
                            success:function (res) {
                                var returnData=res.data;
                                if (returnData) {
                                    layer.msg("添加成功", {icon: 6});
                                    layer.closeAll();

                                    // 重新加载表格
                                    window.parent.location.reload();
                                } else {
                                    layer.msg("添加失败", {icon: 5});
                                }
                            }
                        })
                        return false;//阻止表单跳转,网页url不显示提交的参数。
                    })

                    break;
                case 'update':
                    if(data.length === 0){
                        layer.msg('请选择一行');
                    } else if(data.length > 1){
                        layer.msg('只能同时编辑一个');
                    } else {
                        layer.open({
                            title:'编辑用户信息',
                            type:1,
                            area:['420px','330px'],
                            content:$('#edit_form').html()
                        })
                        form.render()//更新渲染表单

                        // 选择的数据
                        var selectData=data[0];

                        form.val('edit_form',{
                            // 填充表单
                            userName:selectData.userName,
                            userAge:selectData.userAge
                        })

                        // 编辑用户提交
                        form.on('submit(editForm)',function(message){
                            console.log(message.field);
                            console.log(obj.data);

                            var updateObj={
                                "id":selectData.id,
                                "userAge":message.field.userAge,
                                "userName":message.field.userName
                            };

                            $.ajax({
                                url:"/business/user/edit",
                                type:"POST",
                                contentType: "application/json; charset=utf-8",
                                dataType: "json",
                                data: JSON.stringify(updateObj),
                                success:function (res) {
                                    var returnData=res.data;
                                    if (returnData) {
                                        layer.msg("修改成功", {icon: 6});
                                        window.parent.location.reload();
                                    } else {
                                        layer.msg("修改失败", {icon: 5});
                                    }
                                }
                            })
                            return false;//阻止表单跳转,网页url不显示提交的参数。
                        })
                    }
                    break;
                case 'del':
                    if(data.length === 0){
                        layer.msg('请选择一行');
                    } else {
                        layer.confirm('真的删除本条数据?', function(index){
                            obj.del();
                            layer.close(index);
                            $.ajax({
                                type: "DELETE",
                                url: "/business/user/"+ data.id ,
                                data: {"id": data.id},
                                dataType: "json",
                                contentType: "application/json;charset=utf-8",
                                success: function(result) {
                                    if(result.data == true) {
                                        layer.msg("删除成功",{icon: 6});
                                        layer.closeAll();

                                        window.parent.location.reload();
                                    } else {
                                        layer.msg("删除失败",{icon: 5});
                                    }
                                }
                            });
                        });
                    }
                    break;
            };
        });

        //监听行工具事件
        table.on('tool(test)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
            var data = obj.data //获得当前行数据
                ,layEvent = obj.event; //获得 lay-event 对应的值
            if(layEvent === 'detail'){
                layer.open({
                    title:'查看用户信息',
                    type:1,
                    area:['420px','330px'],
                    content:$('#view_form').html()
                })
                form.render()//更新渲染表单
                form.val('view_form',{
                    // 填充表单
                    userName:data.userName,
                    userAge:data.userAge
                })
            } else if(layEvent === 'del'){
                layer.confirm('真的删除本条数据?', function(index){
                    obj.del();
                    layer.close(index);
                    $.ajax({
                        type: "DELETE",
                        url: "/business/user/"+ data.id ,
                        data: {"id": data.id},
                        dataType: "json",
                        contentType: "application/json;charset=utf-8",
                        success: function(result) {
                            if(result.data == true) {
                                layer.msg("删除成功");
                                window.parent.location.reload();
                            } else {
                                layer.msg("删除失败");
                            }
                        }
                    });
                });
            } else if(layEvent === 'edit'){
                layer.open({
                    title:'编辑用户信息',
                    type:1,
                    area:['420px','330px'],
                    content:$('#edit_form').html()
                })
                form.render()//更新渲染表单
                form.val('edit_form',{
                    // 填充表单
                    userName:data.userName,
                    userAge:data.userAge
                })

                // 编辑用户提交
                form.on('submit(editForm)',function(message){
                    console.log(message.field);
                    console.log(obj.data);

                    var updateObj={
                        "id":data.id,
                        "userAge":message.field.userAge,
                        "userName":message.field.userName
                    };

                    $.ajax({
                        url:"/business/user/edit",
                        type:"POST",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        data: JSON.stringify(updateObj),
                        success:function (res) {
                            var returnData=res.data;
                            if (returnData) {
                                layer.msg("修改成功", {icon: 6});
                                window.parent.location.reload();
                            } else {
                                layer.msg("修改失败", {icon: 5});
                            }
                        }
                    })
                    return false;//阻止表单跳转,网页url不显示提交的参数。
                })
            }

        });

        //分页
        laypage.render({
            elem: 'pageDemo' //分页容器的id
            ,count: 100 //总页数
            ,skin: '#1E9FFF' //自定义选中色值
            //,skip: true //开启跳页
            ,jump: function(obj, first){
                if(!first){
                    layer.msg('第'+ obj.curr +'页', {offset: 'b'});
                }
            }
        });

        //底部信息
        var footerTpl = lay('#footer')[0].innerHTML;
        lay('#footer').html(layui.laytpl(footerTpl).render({}))
            .removeClass('layui-hide');
    });
</script>
</body>
</html>
